// src/app/workspace/[workspaceId]/_components/workspace-sidebar.tsx
import React, {useEffect, useState} from 'react';
import {useGetMembers} from "@/features/workspaces/api/use-get-members";
import {useGetMembers as useGetWorkspaceMembers} from "@/features/members/api/use-get-members";
import {useGetWorkspace} from "@/features/workspaces/api/use-get-workspace";
import {useGetWorkspaces} from "@/features/workspaces/api/use-get-workspaces";
import {Channel, Member, Role, Workspace} from "@/lib/social/types";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useCurrentMember} from "@/features/workspaces/api/use-current-member";
import {AlertTriangle, HashIcon, Loader, MessageSquareText, SendHorizonal, SendHorizonalIcon} from 'lucide-react';
import WorkspaceHeader from "@/app/social/workspace/[workspaceId]/_components/workspace-header";
import SidebarItem from "@/app/social/workspace/[workspaceId]/_components/sidebar-item";
import {useGetChannels} from "@/features/channels/api/use-get-channels";
import WorkspaceSection from "@/app/social/workspace/[workspaceId]/_components/workspace-section";
import UserItem from "@/app/social/workspace/[workspaceId]/_components/user-item";
import {useCreateChannelModal} from "@/features/channels/store/use-create-channel-modal";
import {useChannelId} from "@/hooks/social/use-channel-id";
import {useMemberId} from "@/hooks/social/use-member-id";
import {useCurrentUser} from "@/hooks/use-current-user";

const WorkspaceSidebar = () => {
    const user = useCurrentUser()

    const workspaceId = useWorkspaceId()
    const channelId = useChannelId()
    const memberId = useMemberId()

    const [workspace, setWorkspace] = useState<Workspace>();
    const [member, setMember] = useState<Member>();
    const [members, setMembers] = useState<Member[]>();
    const [channels, setChannels] = useState<Channel[]>();

    const [w_loading, setW_loading] = useState(true);
    const [m_loading, setM_loading] = useState(true);
    const [ms_loading, setMs_loading] = useState(true);
    const [c_loading, setC_loading] = useState(true);

    // 创建频道弹窗控制
    const [_open, setOpen] = useCreateChannelModal()

    if (!workspaceId) return <div className={`flex flex-col bg-[5e2c5f] h-full items-center justify-center`}>
        <AlertTriangle className={`size-5 text-white`}/>
        <p className={`text-white text-sm`}>
            Workspace not found
        </p>
    </div>

    useEffect(() => {
        (async () => {
            // 获取当前用户
            const {data: member, isLoading: memberLoading} =
                await useCurrentMember({
                    workspaceId: workspaceId as string,
                    userId: user?.id!
                })
            // 获取当前用户工作区
            const {data, isLoading} =
                await useGetWorkspace({id: workspaceId})
            // 获取当前工作区的频道
            const {data: chanData, isLoading: chanLoading} =
                await useGetChannels({workspaceId})
            // 获取当前工作区的所有成员
            const {
                // @ts-ignore
                data: wMemberData,
                isLoading: wMemberLoading
            } = await useGetWorkspaceMembers({workspaceId})

            setM_loading(memberLoading)
            setW_loading(isLoading)
            setC_loading(chanLoading)
            setMs_loading(wMemberLoading)

            // setMember(member[0])
            setMember(member)
            setWorkspace(data)
            setChannels(chanData)
            setMembers(wMemberData)

            console.log('workspace-sidebar', member, data, chanData, wMemberData)
        })()
    }, [workspaceId, channelId]);

    if (c_loading || m_loading || ms_loading || w_loading) return (
        <div className={`flex flex-col bg-[5e2c5f]x bg-sky-700/80  h-full items-center justify-center`}>
            <Loader className={`size-5 animate-spin text-white`}/>
        </div>
    )

    if (!workspace || !member) return <div
        className={`flex flex-col bg-[5e2c5f]x bg-sky-700/80 h-full items-center justify-center`}>
        <AlertTriangle className={`size-5 text-white`}/>
        <p className={`text-white text-sm`}>
            Workspace not found
        </p>
    </div>

    return (
        <div className={`flex flex-col bg-[5e2c5f]x bg-sky-400/70 h-full`}>
            {/*@ts-ignore*/}
            <WorkspaceHeader isAdmin={(member?.role === Role.ADMIN)} workspace={workspace!}/>
            <div className={`flex flex-col px-2 mt-3`}>
                <SidebarItem
                    label={'Threads'}
                    icon={MessageSquareText}
                    id={'threads'}
                />
                <SidebarItem
                    label={'Drafts & Sent'}
                    icon={SendHorizonal}
                    id={'drafts'}
                />
            </div>
            <WorkspaceSection
                label={'Channels'}
                hint={'New channel'}
                // @ts-ignore
                onNew={member.role === 'admin' ? () => setOpen(true) : undefined}
            >
                {channels?.map((c) => (
                    <SidebarItem
                        key={c.id}
                        label={c.name}
                        icon={HashIcon}
                        id={c.id}
                        variant={channelId === c.id ? 'active' : 'default'}
                    />
                ))}
            </WorkspaceSection>
            <WorkspaceSection
                label={'Direct Messages'}
                hint={'New direct message'}
                onNew={() => {
                }}
            >
                {members?.map((m) => (
                    <UserItem
                        key={m.id}
                        id={m.id}
                        // @ts-ignore
                        label={m.user.name}
                        // @ts-ignore
                        image={m.user.image}
                        variant={m.id === memberId ? 'active' : 'default'}
                    />
                ))}
            </WorkspaceSection>
        </div>
    );
};

export default WorkspaceSidebar;